package get.newsdaily.adapters;

import get.newsdaily.R;
import get.newsdaily.model.RssItem;
import get.newsdaily.utils.variables;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class NewsAdapter extends ArrayAdapter<RssItem> {
	private HashMap<String, Bitmap> bitMap = new HashMap<>();
	private Context context;
	private List<RssItem> items;
	private int paper,layout;
	//private int ivIcon;
	public NewsAdapter(Context context, int layout, List<RssItem> items, int paper) {
		super(context, layout, items);
//		this.ivIcon = ivIcon;
		this.context = context;
		this.paper = paper;
		this.items = items;
		this.layout = layout;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(layout, parent, false);

		ImageView iv = (ImageView) rowView.findViewById(R.id.ivIcon);
		TextView tv = (TextView) rowView.findViewById(R.id.tvNews);

//		iv.setImageResource(ivIcon);
		tv.setText(items.get(position).getTitle()); // Position là vị trí của dòng
		
		iv.setImageResource(variables.ICONS[paper]);
//		return rowView;
		
		//get Img
		if (items.get(position).getDescription() != null) {
			if(bitMap.get(items.get(position).getDescription())!=null) {
				iv.setImageBitmap(bitMap.get(items.get(position).getDescription()));
			}
			
			{new Thread((Runnable) new ListAsynTask(iv).execute(items.get(position).getDescription())).start();
				}
				} else {
				iv.setImageResource(variables.ICONS[paper]);
			}
		return rowView;
		}

		class ListAsynTask extends AsyncTask<String, Void, Bitmap> implements
				Runnable {
			String urldisplay;
			ImageView bmImage;
		

			public ListAsynTask(ImageView bmImage) {

				this.bmImage = bmImage;
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				// if (this.dialog.isShowing()) {//tắt dialog
				// this.dialog.dismiss();
				//
				// }
			bitMap.put(urldisplay, result);
				 bmImage.setImageBitmap(result);
				
			}

			@Override
			protected Bitmap doInBackground(String... params) {
				//String 
				urldisplay = params[0];
				Bitmap mIcon11 = null;
				try {
					InputStream in = new java.net.URL(urldisplay).openStream();
					mIcon11 = BitmapFactory.decodeStream(in);
				} catch (Exception e) {
					Log.e("Error", e.getMessage());
					e.printStackTrace();
				}
				return mIcon11;

			}

			@Override
			public void run() {

			}
	}

}
